package pers.cz.config;

import pers.cz.filter.*;
import pers.cz.pub.RespBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @program: PostGirl-panent
 * @description: SecurityConfig
 * @author: Cheng Zhi
 * @create: 2021-04-20 12:39
 **/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    Logger logger= LoggerFactory.getLogger(SecurityConfig.class);

    @Autowired
    CustomAccessDecisionManager customAccessDecisionManager;

    @Autowired
    CustomSecurityMetadataSource customSecurityMetadataSource;

    @Autowired
    JedisPool jedisPool;

    /**
     * 配置加密规则
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){

        return new BCryptPasswordEncoder();
    }

    /**
     * 配置显示用户找不到异常，如果不配置默认为true,为ture表示隐藏错误信息，展示BadCredentialsException异常
     * @return
     */
    @Bean
    public Boolean hideUserNotFoundExceptions() {
        return false;
    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * access permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {

            http.csrf().disable();
            http
                //允许跨域
                .cors().and().anonymous().and()
                // CRSF禁用，因为不使用session
                    // .csrf().disable()
                    //.csrf().requireCsrfProtectionMatcher(requestMatcher())
                // 认证失败处理类
                //.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 验证码captchaImage 允许匿名访问
                //.antMatchers("/login", "/captchaImage").anonymous()
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                .antMatchers("/profile/**").anonymous()
                .antMatchers("/common/download**").anonymous()
                .antMatchers("/common/download/resource**").anonymous()
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                .antMatchers("/druid/**").anonymous()
                .antMatchers("/static/**").anonymous()
                .antMatchers("/websocket/**").anonymous()
                .antMatchers("/api/test/**").anonymous()
                .antMatchers("/api/verifyCodeController/**").anonymous()
                .antMatchers("/api/verifyCodeController/**").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();

            http.logout().logoutUrl("/api/logout")
                .logoutSuccessHandler(
                        new LogoutSuccessHandler() {
                            @Override
                            public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                                // 注销登录
                                resp.setContentType("application/json;charset=utf-8");
                                PrintWriter out = resp.getWriter();
                                String s = new ObjectMapper().writeValueAsString(RespBean.ok("注销成功"));
                                out.write(s);
                                out.flush();
                                out.close();
                            }
                        }
                ).invalidateHttpSession(true); // 注销时让session失效
        http.addFilterAfter(customerFilter(), FilterSecurityInterceptor.class);
        http.addFilterBefore(new JwtLoginFilter("/api/doLogin",authenticationManager(), jedisPool), UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(new JwtCheckFilter(), UsernamePasswordAuthenticationFilter.class);

    }

    /**
     * 自定义拦截器
     * @return
     */
    public CustomFilterSecurityInterceptor customerFilter() {
        CustomFilterSecurityInterceptor customFilter = new CustomFilterSecurityInterceptor();
        customFilter.setSecurityMetadataSource(customSecurityMetadataSource);
        customFilter.setAccessDecisionManager(customAccessDecisionManager);
        return  customFilter;
    }
}
